package com.docker.apps.afterservice.ui;

import android.arch.lifecycle.ViewModelProviders;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import com.dcbfhd.utilcode.utils.ToastUtils;
import com.docker.apps.R;
import com.docker.apps.afterservice.utils.BundleMap;
import com.docker.apps.afterservice.vm.AfterServiceViewModel;
import com.docker.apps.databinding.ProAfterServiceFragmentBinding;
import com.docker.apps.order.vo.InvoiceVov2;
import com.docker.apps.order.vo.entity.InvoiceEntity;
import com.docker.common.common.adapter.CommonpagerAdapter;
import com.docker.common.common.command.NitDelegetCommand;
import com.docker.common.common.config.Constant;
import com.docker.common.common.model.CommonListOptions;
import com.docker.common.common.ui.base.NitCommonFragment;
import com.docker.common.common.ui.container.NitCommonContainerFragmentV2;
import com.docker.common.common.utils.ParamUtils;
import com.docker.common.common.utils.cache.CacheUtils;
import com.docker.common.common.utils.rxbus.RxBus;
import com.docker.common.common.utils.rxbus.RxEvent;
import com.docker.common.common.vm.NitCommonListVm;
import com.docker.common.common.widget.XPopup.BottomPopup;
import com.docker.common.common.widget.indector.CommonIndector;
import com.google.gson.internal.LinkedTreeMap;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.core.BasePopupView;
import com.lxj.xpopup.interfaces.XPopupCallback;

import java.util.ArrayList;

import io.reactivex.disposables.Disposable;

public class AfterProcessFragment extends NitCommonFragment<AfterServiceViewModel, ProAfterServiceFragmentBinding> {

    private BundleMap bundleMap;

    private InvoiceEntity invoiceEntity;

    public static AfterProcessFragment getInstance(BundleMap bundleMap) {

        AfterProcessFragment afterProcessFragment = new AfterProcessFragment();
        Bundle bundle = new Bundle();
        bundle.putSerializable("map", bundleMap);
        afterProcessFragment.setArguments(bundle);
        return afterProcessFragment;
    }


    @Override
    protected int getLayoutId() {
        return R.layout.pro_after_service_fragment;
    }

    @Override
    protected AfterServiceViewModel getViewModel() {
        return ViewModelProviders.of(this, factory).get(AfterServiceViewModel.class);
    }

    @Override
    protected void initView(View var1) {

    }


    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        bundleMap = (BundleMap) getArguments().getSerializable("map");
        peocessTab();

    }

    @Override
    public NitDelegetCommand providerNitDelegetCommand(int flag) {

        NitDelegetCommand nitDelegetCommand = null;

        nitDelegetCommand = new NitDelegetCommand() {
            @Override
            public Class providerOuterVm() {
                return AfterServiceViewModel.class;
            }

            @Override
            public void next(NitCommonListVm commonListVm, NitCommonFragment nitCommonFragment) {
                ((AfterServiceViewModel) commonListVm).state = flag;
                ((AfterServiceViewModel) commonListVm).isAfterService = 1;
                ((AfterServiceViewModel) commonListVm).mDelInvoiceLv.observe(nitCommonFragment, s -> {

                });

                ((AfterServiceViewModel) commonListVm).mModifyInvoiceLv.observe(nitCommonFragment, invoiceVov2 -> {
                    showInvoice(invoiceVov2, ((AfterServiceViewModel) commonListVm));
                });


                ((AfterServiceViewModel) commonListVm).mInvoiceLv.observe(nitCommonFragment, s -> {
                    ToastUtils.showLong("修改成功");
                    if (bottomPopup != null) {
                        bottomPopup.dismiss();
                    }
                    RxBus.getDefault().post(new RxEvent<>("updateAfterService", ""));
                });
            }
        };
        return nitDelegetCommand;
    }

    BottomPopup bottomPopup;

    ///发票
    private void showInvoice(InvoiceVov2 invoiceVov2, AfterServiceViewModel afterServiceViewModel) {

        bottomPopup = new BottomPopup(this.getHoldingActivity(), "invoice");

        BasePopupView basePopupView = new XPopup.Builder(this.getHoldingActivity()).setPopupCallback(new XPopupCallback() {
            @Override
            public void onCreated() {

            }

            @Override
            public void beforeShow() {

            }

            @Override
            public void onShow() {
                ImageView iv_close = bottomPopup.findViewById(com.docker.common.R.id.iv_close);
                iv_close.setOnClickListener(v ->
                        bottomPopup.dismiss());

                RadioGroup riseGroup = bottomPopup.findViewById(R.id.rise_type);//普通 增至
                RadioGroup personGroup = bottomPopup.findViewById(R.id.person_type);//个人 公司


                RadioButton putongButton = bottomPopup.findViewById(R.id.in1);//普通
                RadioButton zengButton = bottomPopup.findViewById(R.id.in2);//增值税

                if ("1".equals(invoiceVov2.type)) {
                    putongButton.setChecked(true);
                } else {
                    zengButton.setChecked(true);
                }


                RadioButton grButton = bottomPopup.findViewById(R.id.in3);//个人
                RadioButton dwButton = bottomPopup.findViewById(R.id.in4);//公司

                if ("1".equals(invoiceVov2.role)) {
                    grButton.setChecked(true);
                } else {
                    dwButton.setChecked(false);
                }

                LinearLayout grenLiner1 = bottomPopup.findViewById(R.id.geren_liner);//个人名称
                LinearLayout companyLiner = bottomPopup.findViewById(R.id.company_liner);

                Button subBtn = bottomPopup.findViewById(R.id.sub1);//
                EditText grnameEdit = bottomPopup.findViewById(R.id.geren1);//个人名称

                grnameEdit.setText(invoiceVov2.name);

                EditText namesprEdit = bottomPopup.findViewById(R.id.ed_spr_name);//收票人姓名
                namesprEdit.setText(invoiceVov2.receiveName);

                EditText phonesprEdit = bottomPopup.findViewById(R.id.ed_spr_phone);//收票人手机号
                phonesprEdit.setText(invoiceVov2.receiveTel);

                EditText adressprEdit = bottomPopup.findViewById(R.id.ed_spr_addresss);//收票人地址
                adressprEdit.setText(invoiceVov2.receiveAddress);


                EditText dwdwname = bottomPopup.findViewById(R.id.ed_dw_name);//单位名称
                dwdwname.setText(invoiceVov2.companyName);

                EditText dwnsrsbh = bottomPopup.findViewById(R.id.ed_dw_sbm);//纳税人号
                dwnsrsbh.setText(invoiceVov2.taxNumber);

                EditText dwaddress = bottomPopup.findViewById(R.id.ed_dw_address);//单位dizhi
                dwaddress.setText(invoiceVov2.companyAddress);

                EditText dwtel = bottomPopup.findViewById(R.id.ed_dw_phone);//电话
                dwtel.setText(invoiceVov2.companyTel);


                putongButton.setOnCheckedChangeListener((buttonView, isChecked) -> {
                    if (isChecked) {
                        grenLiner1.setVisibility(View.VISIBLE);
                        grButton.setVisibility(View.VISIBLE);
                        grButton.setChecked(true);
                        companyLiner.setVisibility(View.GONE);
                    }
                });
                grButton.setOnCheckedChangeListener((buttonView, isChecked) -> {
                    if (isChecked) {
                        grenLiner1.setVisibility(View.VISIBLE);
                        companyLiner.setVisibility(View.GONE);
                    }
                });

                dwButton.setOnCheckedChangeListener((buttonView, isChecked) -> {
                    if (isChecked) {
                        grenLiner1.setVisibility(View.GONE);
                        companyLiner.setVisibility(View.VISIBLE);
                    }
                });

                zengButton.setOnCheckedChangeListener((buttonView, isChecked) -> {
                    if (isChecked) {
                        grenLiner1.setVisibility(View.GONE);
                        dwButton.setChecked(true);
                        grButton.setVisibility(View.GONE);
                        companyLiner.setVisibility(View.VISIBLE);
                    }
                });

                subBtn.setOnClickListener(v -> {
                    invoiceEntity = new InvoiceEntity();
                    invoiceEntity.memberid = CacheUtils.getUser().uid;
                    invoiceEntity.orderid = invoiceVov2.orderid;
                    invoiceEntity.invoiceId = invoiceVov2.id;

                    invoiceEntity.type = putongButton.isChecked() ? "1" : "2";
                    invoiceEntity.role = grButton.isChecked() ? "1" : "2";


                    if (grButton.isChecked()) {
                        invoiceEntity.name = grnameEdit.getText().toString();
                        if (TextUtils.isEmpty(invoiceEntity.name)) {
                            ToastUtils.showShort("请填写个人名称");
                            return;
                        }
                    }
                    if (dwButton.isChecked()) {
                        invoiceEntity.companyName = dwdwname.getText().toString();
                        if (TextUtils.isEmpty(invoiceEntity.companyName)) {
                            ToastUtils.showShort("请填写单位名称");
                            return;
                        }
                        invoiceEntity.Identifier = dwnsrsbh.getText().toString();
                        if (TextUtils.isEmpty(invoiceEntity.Identifier)) {
                            ToastUtils.showShort("请填写纳税人识别号");
                            return;
                        }
                        invoiceEntity.companyAddress = dwaddress.getText().toString();
                        if (TextUtils.isEmpty(dwaddress.getText().toString())) {
                            ToastUtils.showShort("请填写单位地址");
                            return;
                        }
                        invoiceEntity.companyTel = dwtel.getText().toString();
                        if (TextUtils.isEmpty(dwtel.getText().toString())) {
                            ToastUtils.showShort("请填写单位电话");
                            return;
                        }
                    }

                    invoiceEntity.receiveName = namesprEdit.getText().toString();
                    if (TextUtils.isEmpty(namesprEdit.getText().toString())) {
                        ToastUtils.showShort(namesprEdit.getHint());
                        return;
                    }
                    invoiceEntity.receiveTel = phonesprEdit.getText().toString();
                    if (TextUtils.isEmpty(phonesprEdit.getText().toString())) {
                        ToastUtils.showShort(phonesprEdit.getHint());
                        return;
                    }
                    invoiceEntity.receiveAddress = adressprEdit.getText().toString();
                    if (TextUtils.isEmpty(adressprEdit.getText().toString())) {
                        ToastUtils.showShort(adressprEdit.getHint());
                        return;
                    }
                    afterServiceViewModel.addInvoice((LinkedTreeMap<String, String>) ParamUtils.obj2map(invoiceEntity));
                });
            }

            @Override
            public void onDismiss() {

            }

            @Override
            public boolean onBackPressed() {
                return false;
            }
        }).asCustom(bottomPopup);

        basePopupView.show();
    }


    public ArrayList<Fragment> fragments = new ArrayList<>();

    public void peocessTab() {


        for (int i = 0; i < bundleMap.maps.size(); i++) {
            CommonListOptions commonListOptions1 = new CommonListOptions();
            commonListOptions1.refreshState = Constant.KEY_REFRESH_OWNER;
            commonListOptions1.isActParent = false;
            commonListOptions1.falg = bundleMap.flag[i];
            commonListOptions1.ReqParam = bundleMap.maps.get(i);
            NitCommonContainerFragmentV2 nitCommonContainerFragmentV21 = NitCommonContainerFragmentV2.newinstance(commonListOptions1);
            fragments.add(nitCommonContainerFragmentV21);
        }

        // magic
        mBinding.get().viewPager.setAdapter(new CommonpagerAdapter(this.getChildFragmentManager(), fragments, bundleMap.title));
        CommonIndector commonIndector = new CommonIndector();
        commonIndector.initMagicIndicator(bundleMap.title, mBinding.get().viewPager, mBinding.get().magicIndicator, this.getHoldingActivity());


    }


    private Disposable disposable;

    private void initDisposable() {
        disposable = RxBus.getDefault().toObservable(RxEvent.class).subscribe(rxEvent -> {
            if (rxEvent.getT().equals("updateAfterService")&&mBinding.get()!=null&&mBinding.get().viewPager!=null) {
                NitCommonContainerFragmentV2 nitCommonContainerFragmentV2 = (NitCommonContainerFragmentV2) fragments.get(mBinding.get().viewPager.getCurrentItem());
                if (nitCommonContainerFragmentV2 != null)
                    nitCommonContainerFragmentV2.mViewModel.mItems.clear();
                nitCommonContainerFragmentV2.onReFresh(null);
            }
        });
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initDisposable();
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        if (disposable != null) disposable.dispose();
        disposable = null;
    }

    @Override
    public void initImmersionBar() {

    }
}
